

<template>
    <div>
        <input type="file" @change="handleImageUpload" style="display: none;" ref="fileInput"
            accept="image/gif, image/jpeg,image/png">
        <div class="avatar-preview">
            <img :src="uploadedImage" class="avatar" v-if="uploadedImage" v-cloak>
        </div>
        <div class="personDiv">
            <el-button type="info" plain class="personBtn" @click="watch">查看头像</el-button>
            <el-button type="info" plain class="personBtn" @click="abb">上传头像</el-button>
            <el-button type="info" plain class="personBtn" @click="editpass">修改密码</el-button>
        </div>



        <!-- 查看头像 -->
        <el-dialog title="历史头像" :visible.sync="watchDialog" width="50%">
            <el-form style="overflow: scroll; height: 500px;">
                <img v-for="(v, i) in img" :src="v.image" :key="i" :class="{ 'avatar': true, 'sel': select === i }"
                    style="width: 200px; height: 200px; margin-left: 20px;margin-top: 20px; box-sizing: border-box;"
                    @click="choose(v, i)">
            </el-form>
            <span slot="footer" class="dialog-footer">
                <el-button @click="watchDialog = false">取 消</el-button>
                <el-button type="primary" @click="surewatch">使用</el-button>
            </span>
        </el-dialog>


        <!-- 修改弹出框 -->
        <el-dialog title="修改密码" :visible.sync="editDialog" width="30%">
            <el-form :model="editData" :rules="rules" ref="editData">
                <el-form-item label="账号" :label-width="formLabelWidth">
                    <el-input v-model="editData.tel" autocomplete="off" disabled></el-input>
                </el-form-item>
                <el-form-item label="密码" :label-width="formLabelWidth" prop="password">
                    <el-input v-model="editData.password" autocomplete="off" type="password" show-password></el-input>
                </el-form-item>

            </el-form>
            <span slot="footer" class="dialog-footer">
                <el-button @click="editDialog = false">取 消</el-button>
                <el-button type="primary" @click="submitForm('editData')">确定修改</el-button>
            </span>
        </el-dialog>
    </div>
</template>
  
<script>
import { openDB } from 'idb';

export default {
    data() {
        return {
            watchDialog: false,
            editDialog: false,
            formLabelWidth: '100px',
            uploadedImage: require('../../assets/images/head.png'),
            db: null,
            img: [],
            chooseimg: '',
            select: 0,
            editData: {
                id: '',
                tel: '',
                password: ''
            },
            rules: {
                password: [
                    { required: true, message: '请输入密码', trigger: 'blur' },
                    { pattern: /^\d{3,9}$/, message: '密码修改有误', trigger: 'blur' }
                ],
            }
        };
    },
    methods: {
        async handleImageUpload(event) {
            const file = event.target.files[0];
            //限制文件类型
            let suffixName = file.name.substring(file.name.lastIndexOf('.') + 1);   /* 得到文件后缀名 */
            if (suffixName !== 'jpg' && suffixName !== 'png' && suffixName !== 'gif') {
                this.$message.warning("上传文件只能是 jpg、png 格式!");
                return;
            }

            /* 限制文件上传大小 */
            let isLtSize = file.size / 1024 / 1024 < 10;
            if (!isLtSize) {
                this.$message.warning("上传文件不能超过 10MB!");
                return;
            }


            if (file) {
                const reader = new FileReader();

                reader.onload = async (e) => {
                    const imageUrl = e.target.result;
                    // 打开IndexedDB版本库
                    if (!this.db) {
                        this.db = await openDB('my-database', 1, {
                            upgrade(db) {
                                db.createObjectStore('images', { keyPath: "id", autoIncrement: true });    //创建库
                            }
                        });
                    }

                    // 保存图片数据到IndexedDB数据库
                    const tx = this.db.transaction('images', 'readwrite');  //启动库，并且设置为可写入
                    const store = tx.objectStore('images');     //获取库
                    await store.add({
                        image: e.target.result,
                        headtel: JSON.parse(sessionStorage.getItem('登录信息')).username
                    });//添加时给一个key键

                    // 更新上传的图片
                    this.uploadedImage = imageUrl;
                    this.$store.commit('changehead', this.uploadedImage)
                    this.$message({
                        message: '修改成功',
                        type: 'success',
                        duration: 1400
                    })
                };

                reader.readAsDataURL(file);
            }
        },
        abb() {
            this.$refs.fileInput.click()
        },
        choose(v, i) {
            this.chooseimg = v.image
            this.select = i
        },
        async watch() {
            this.img = []
            this.watchDialog = true
            if (!this.db) {
                this.db = await openDB('my-database', 1, {
                    upgrade(db) {
                        db.createObjectStore('images', { keyPath: "id", autoIncrement: true });
                    }
                });
            }

            const store = this.db.transaction('images').objectStore('images');
            const images = await store.getAll();
            images.forEach((v) => {
                if (v.headtel === JSON.parse(sessionStorage.getItem('登录信息')).username) {
                    this.img.push(v)
                }
            })
            this.select = this.img.length - 1
            this.chooseimg = this.img[this.img.length - 1].image
        },
        async surewatch() {
            this.watchDialog = false
            const imageUrl = this.chooseimg
            // 打开IndexedDB版本库
            if (!this.db) {
                this.db = await openDB('my-database', 1, {
                    upgrade(db) {
                        db.createObjectStore('images', { keyPath: "id", autoIncrement: true });    //创建库
                    }
                });
            }

            // 保存图片数据到IndexedDB数据库
            const tx = this.db.transaction('images', 'readwrite');  //启动库，并且设置为可写入
            const store = tx.objectStore('images');     //获取库
            await store.add({
                image: imageUrl,
                headtel: JSON.parse(sessionStorage.getItem('登录信息')).username
            });//添加时各一个key键

            // 更新上传的图片
            this.uploadedImage = imageUrl;
            this.$store.commit('changehead', this.uploadedImage)

            this.$message({
                message: '修改成功',
                type: 'success',
                duration: 1400
            })
        },
        editpass() {
            this.editDialog = true
            this.editData.tel = JSON.parse(sessionStorage.getItem('登录信息')).tel
            this.editData.id = JSON.parse(sessionStorage.getItem('登录信息')).id
            this.editData.password = JSON.parse(sessionStorage.getItem('登录信息')).password
        },
        submitForm(formName) {
            this.$refs[formName].validate((valid) => {
                if (valid) {
                    this.editDialog = false
                    this.$axios({
                        url: `/admin/${this.editData.id}`,
                        method: 'patch',
                        data: {
                            password: this.editData.password
                        }
                    }).then(({ data }) => {
                        if (data) {
                            this.$message({
                                message: '修改成功',
                                type: 'success',
                                duration: 1400
                            })
                            this.$router.push('/')
                            location.reload()
                        }
                    })
                }
            });
        }
    },
    async mounted() {
        // 页面加载时，从IndexedDB数据库中恢复上传的图片
        if (!this.db) {
            this.db = await openDB('my-database', 1, {
                upgrade(db) {
                    db.createObjectStore('images', { autoIncrement: true });
                }
            });
        }

        const store = this.db.transaction('images').objectStore('images');
        const images = await store.getAll();
        // console.log(images)
        images.forEach((v) => {
            if (v.headtel === JSON.parse(sessionStorage.getItem('登录信息')).username) {
                this.img.push(v)
            }
        })
        if (this.img.length > 0 && JSON.parse(sessionStorage.getItem('登录信息')).username == this.img[this.img.length - 1].headtel) {
            this.uploadedImage = this.img[this.img.length - 1].image;
        }
    }
};
</script>
<style lang="less" scoped>
.avatar-preview {
    /* position: relative; */
    width: 240px;
    height: 240px;
    margin: 0 auto;
    margin-top: 10px;
}

.avatar {
    width: 100%;
    height: 100%;
    object-fit: cover;
    border-radius: 50%;
    cursor: pointer;
}

.personDiv {
    display: flex;
    flex-direction: column;
    justify-content: space-between;
    align-items: center;
    width: 300px;
    height: 300px;
    margin: 50px auto;

    .personBtn {
        width: 300px;
        height: 50px;
        display: block;
    }
}

.sel {
    border: 4px solid #333;
}

.addDiv {
    margin-right: 60px;
}

[v-cloak] {
    display: none;
}
</style>